package com.cjd.common.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cjd.common.R;
import com.cjd.common.utils.CommonUtil;

import java.io.File;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;


/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/7/2
 * description activity 拍照或选择相册图片基类
 */

public abstract class BasePhotoActivity extends BaseDesignActivity {

    private Dialog mDialog;
    private File cameraFile = null;
    private static final int REQUEST_CODE_CAMERA = 0;
    private static final int REQUEST_CODE_LOCAL = 1;
    private boolean isGranted = false;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists())
                    onPhotoCallback(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null)
                        sendPicByUri(selectedImage);
                }
            }
        }
    }

    /**
     * 菜单选择 相机
     */
    protected void selectPicFromCamera() {
        if (!CommonUtil.isExistSDCard()) {
            return;
        }
        cameraFile = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + ".png");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 菜单选择  相册
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }


    /**
     * 显示菜单
     */
    protected void showDialogMenu() {
        isGranted = false;

        onRuntimePermissionRequest(new Function1<List<String>, Unit>() {
            @Override
            public Unit invoke(List<String> deniedPermissionList) {
                if (!deniedPermissionList.isEmpty()) {
                    isGranted = false;
                    Toast.makeText(BasePhotoActivity.this, R.string.base_photo_unauthorized, Toast.LENGTH_SHORT).show();
                } else
                    isGranted = true;
                return null;
            }
        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (!isGranted)
            return;

        if (mDialog == null) {
            mDialog = onCreateDialogMenu();
            if (mDialog == null)
                mDialog = defaultDialog();
        }
        mDialog.show();
    }

    /**
     * 默认的 dialog 菜单
     *
     * @return dialog
     */
    private Dialog defaultDialog() {
        View view = this.getLayoutInflater().inflate(R.layout.base_dialog_photo, null);
        Button cancel = view.findViewById(R.id.btn_cancel);
        Button camera = view.findViewById(R.id.btn_camera);
        Button album = view.findViewById(R.id.btn_album);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPicFromCamera();
                mDialog.dismiss();
            }
        });
        album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPicFromLocal();
                mDialog.dismiss();
            }
        });

        Dialog dialog = new Dialog(this, R.style.MaterialDialogSheet);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.getWindow().setGravity(Gravity.BOTTOM);

        return dialog;
    }


    /**
     * 处理 相册或照片回调
     *
     * @param selectedImage 临时url
     */
    private void sendPicByUri(Uri selectedImage) {
        Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex("_data");
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;
            if (picturePath == null || "null".equals(picturePath)) {
                return;
            }
            onPhotoCallback(picturePath);
        } else {
            if (!TextUtils.isEmpty(selectedImage.getPath())) {
                File file = new File(selectedImage.getPath());
                if (!file.exists()) {
                    return;
                }
                onPhotoCallback(file.getAbsolutePath());
            }
        }
    }

    /**
     * 拍照或相册选择回调
     *
     * @param filePath 临时路径
     */
    public abstract void onPhotoCallback(final String filePath);

    /**
     * 自定义 dialog 菜单 需要 手动调用相机或相册
     *
     * @return Dialog
     */
    public abstract Dialog onCreateDialogMenu();

}
